import { ref, reactive, toRefs } from 'vue'
import request from '@/utils/request.js'

// ======================================
// 1. 请求参数类型定义（严格 TypeScript 约束）
// ======================================
interface deepseekRequest {
     convId: String,
    apiKey: String,
    query: String,
    model: String,
}

// ======================================
// 2. 响应结果类型（泛型增强 + 语义化）
// ======================================
interface BaseResponse<T = any> {
    code?: number
    message?: string
    data?: T        // 泛型支持具体类型
    timestamp?: number
}




// ======================================
// 3. 通用请求工具（消除重复逻辑）
// ======================================
const baseRequest = async <T>(
    state: {
        loading: boolean
        error: string | null
        response: BaseResponse<T> | null
    },
    url: string,
    method: 'GET' | 'POST',
    params?: Record<string, any>, // GET 参数
    data?: Record<string, any>    // POST 请求体
): Promise<BaseResponse<T>> => {
    state.loading = true
    state.error = null
    state.response = null

    try {
        const response = await request({ url, method, params, data })
        state.response = response as BaseResponse<T>
        return response
    } catch (error: any) {
        state.error = error.message || '请求失败'
        throw error // 抛出错误供上层处理
    } finally {
        state.loading = false
    }
}


// ======================================
// 4. 业务方法 & 状态管理（清晰隔离）
// ======================================
export const useDeepseekService = () => {
    // 每个方法独立管理状态，避免混淆
    const deepseekState = reactive({
        loading: false,
        error: null as string | null,
        response: null as BaseResponse<string> | null,
    })
    // -------------------- 与ai对话 --------------------
    const deepseek = async (params: deepseekRequest) => {
        return baseRequest<string>(deepseekState, '/api/deepseek/notstream', 'POST', undefined, params)
    }

    // ======================================
    // 5. 导出响应式状态 & 方法
    // ======================================
    return {
        ...toRefs(deepseekState),
        deepseek
    }
}